package com.tony.easymvc.core;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

import com.google.common.collect.Lists;
import com.tony.easymvc.TemplateUtils;
import com.tony.easymvc.core.bean.GeneratorManifest;
import com.tony.easymvc.script.Template;
import com.tony.easymvc.script.TemplateImpl;

public class FileGenerator {

    private List<GeneratorManifest> manifests = Lists.newArrayList();

    public static final String      CHARSET   = "utf8";

    public FileGenerator(List<GeneratorManifest> manifests) {
        super();
        this.manifests = manifests;
    }

    public void generator(Map<String, Object> c) throws IOException {
        generator(c, false);
    }

    public void generator(Map<String, Object> c, boolean isAppend) throws IOException {
        for (int i = 0; i < manifests.size(); i++) {
            GeneratorManifest manifest = manifests.get(i);
            boolean _isAppend = isAppend ? isAppend : manifest.isAppend();
            generator(manifest, c, _isAppend);
        }
    }

    private void generator(GeneratorManifest manifest, Map<String, Object> c, boolean isAppend) throws IOException {
        String content = resolve(manifest, c);
        writerFile(manifest, content, isAppend);
    }

    private void writerFile(GeneratorManifest manifest, String content, boolean isAppend) throws UnsupportedEncodingException, FileNotFoundException, IOException {
        String fp = manifest.getPath() + "/" + manifest.getFilename();
        File f = new File(fp);
        mkdirs(manifest);
        BufferedWriter writer = null;
        try {
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f, isAppend), CHARSET));
            writer.write(content.trim());
            writer.newLine();
            writer.flush();
        } finally {
            writer.close();
        }
    }

    private void mkdirs(GeneratorManifest manifest) {
        try {
            new File(manifest.getPath()).mkdirs();
        } catch (Exception e) {
            throw e;
        }
    }

    private String resolve(GeneratorManifest manifest, Map<String, Object> c) throws IOException {
        String tmp = TemplateUtils.loadTempl(manifest.getTmplName());
        Template t = new TemplateImpl(manifest.getTmplName(), tmp);
        return t.resolve(c);
    }
}
